package com.htjc.integral.conversion.service.impl;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.commons.service.util.StringUtil;
import com.commons.service.util.UUIDGenerator;
import com.commons.service.util.json.JsonUtil;
import com.htjc.integral.conversion.conf.RedisTem;
import com.htjc.integral.conversion.enums.Constant;
import com.htjc.integral.conversion.mapper.EcRequestLogMapper;
import com.htjc.integral.conversion.mapper.EcSystemParamMapper;
import com.htjc.integral.conversion.service.ICorporationBoundManagerService;
import com.htjc.integral.conversion.service.IEcBpExchangeManagerService;
import com.htjc.integral.conversion.service.IEcCorporationBoundService;
import com.htjc.integral.conversion.service.IEcbpExchangeService;
import com.htjc.integral.conversion.service.IGdtService;
import com.htjc.integral.model.conversion.EcRequestLog;
import com.htjc.integral.model.conversion.EcSystemparam;
import com.sgcc.sip.access.rest.SipRestAccessAgent;
import com.sgcc.sip.access.rest.SipRestAccessAgentFactory;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "conversionLogger")
@Service
public class EcBpExchangeManagerServiceImpl implements IEcBpExchangeManagerService {
	private String uscBaseUrl = "";
	

	@Autowired
	private RedisTem redisTem;
	
	@Autowired
	IEcbpExchangeService ecbpExchangeServiceImpl;
	
	@Autowired
	IGdtService gdtServiceImpl;
	
	@Autowired
	IEcCorporationBoundService ecCorporationBoundServiceImpl;
	
	@Autowired
	private ICorporationBoundManagerService corporationBoundManagerServiceImpl;
	
	@Autowired
	private EcSystemParamMapper ecSystemParamMapper;
	
	@Autowired
	EcRequestLogMapper ecRequestLogMapper;
	
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	//111
	/**
	 * return lists;
	 * Map
	 */
	@Override
	public Map<String, Object> queryCorExchange(String corporationId,
			String applicationNo, Date nowDate) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("corporationId", corporationId);
		map.put("applicationNo", applicationNo);
		map.put("nowDate", nowDate);
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		try {
			log.info("EcBpExchangeManagerServiceImpl-->getOneScoreConver--->map="+map.toString());
			lists = this.ecbpExchangeServiceImpl.queryCorExchange(map);
			log.info("EcBpExchangeManagerServiceImpl-->getOneScoreConver--->lists="+lists.size());
		} catch (Exception e) {
			log.info("查询出错："+e.getMessage());
			e.printStackTrace();
		}
		if(lists!=null && lists.size()!=0){
			return lists.get(0);
		}
		return null;
	}
	
	//111
	private String checkContain(List<String> list){
		Map<String,Object> map = new HashMap<String,Object>();
		if(list!=null&&list.size()!=0){ 
			if(list.contains("0")){
				map.put("flag", "0");
				map.put("message", "转换成功");
			}else{
				if(list.contains("2")){
					//接口未返回详情数据
					map.put("flag", "2");
					map.put("message", "转换异常，请重试");
				}else if(list.contains("3")){
					//不存在积分比例
					map.put("flag", "3");
					map.put("message", "当前活动未开启，敬请期待");
				}else if(list.contains("1")){
					//转换积分为0
					map.put("flag", "1");
					map.put("message", "您绑定的用电编号的积分已全部转换");
				}else if(list.contains("4")){
					map.put("flag", "4");
					map.put("message", "商城积分剩余积分不足，暂不支持积分兑换。");
				}else if(list.contains("5")){
					map.put("flag", "5");
					map.put("message", "正在兑换，请稍等。。。");
				}else if(list.contains("9")){
					map.put("flag", "9");
					map.put("message", "积分兑换不成功，请您重新兑换！");
				}else if(list.contains("11")){
					map.put("flag", "11");
					map.put("message", "已解绑，暂不支持积分兑换。");
				}else if(list.contains("12")){
					map.put("flag", "12");
					map.put("message", "根据转换比例，输入的积分值太小！");
				}else if(list.contains("15")){
					map.put("flag", "15");
					map.put("message", "该省份不支持手动转换，只支持统一积分平台推送转换！");
				}
			}
		}
		return JsonUtil.getInstance().map2Json(map);
	}
	//111
	@Override
	public String scoreConvertByOne(String partnerId,String consNo,String orgNo,String score) {
		List<String> reStr = new ArrayList<String>();
		score=score.indexOf(".")>-1?score.substring(0,score.indexOf(".")):score;
		try {
			log.info("绑定列表查询条件==>partnerId:{}, corporationId:{}, applicationUserCode:{}, addressCard:{}",partnerId,null, consNo, orgNo);
			List<Map<String,String>> boundList = this.corporationBoundManagerServiceImpl.checkMobile(partnerId, null, consNo, orgNo);
			if(boundList!=null&&boundList.size()!=0){
//				Map<String, Object> detailQuery = null;
				Map<String, Object> detailQuery = new HashMap<String, Object>();
				if(getIsOpenProvince(orgNo)){
					return "{'flag': '15','message':'该省份不支持手动转换，只支持统一积分平台推送转换！'}";
//					detailQuery = this.gdtServiceImpl.queryScoreDetailForNew(consNo, orgNo, partnerId);
//					log.info("scoreConvertByOne++++++++++++++++++++++++detailQuery1："+detailQuery);
				}else{
//					detailQuery = this.gdtServiceImpl.queryScoreDetail(consNo, orgNo);//===================aaa==================
					detailQuery.put("score", "420");//传回的电力积分
					detailQuery.put("consNo", "8102030921");//用电户号
					detailQuery.put("orgNo", "420000");//网省编码
					//detailQuery.put("fromxml", "");//fromxml
					//detailQuery.put("toxml", "");//toxml
					log.info("scoreConvertByOne++++++++++++++++++++++++detailQuery2："+detailQuery);
				}
				 
				if(MapUtils.isNotEmpty(detailQuery)){
					log.info("EcBpExchangeManagerServiceImpl.java--->detailQuery："+detailQuery);
					String reScore = String.valueOf(detailQuery.get("score"));
					log.info("scoreConvertByOne++++++++++++++++++++++++reScore："+reScore);
					reScore=reScore.indexOf(".")>-1?reScore.substring(0,reScore.indexOf(".")):reScore;
					if(Integer.valueOf(score).compareTo(Integer.valueOf(reScore))<=0){
						Calendar calendar = Calendar.getInstance();
						String corporationId = boundList.get(0).get("CORPORATION_ID"); 
						String boundCorId = boundList.get(0).get("ID");
						consNo = String.valueOf(detailQuery.get("consNo"));
						orgNo = String.valueOf(detailQuery.get("orgNo"));
						if(Integer.valueOf(reScore)>0){
							String retVal = scoreConvert(partnerId, consNo, orgNo, score, reScore, calendar, corporationId,	boundCorId);
							log.info("EcBpExchangeManagerServiceImpl.java--->retVal："+retVal);
							reStr.add(retVal);
						}else{
							return "{'flag': '1','message':'您绑定的用电编号的积分已全部转换'}";
						}
					}else{
						return "{'flag':'1','message':'输入积分值不能大于实际值'}";
					}
				}else{
					return "{'flag':'1','message':'转换异常，请重试'}";
				}
			}else{
				return "{'flag': '1','message':'用户编号不存在'}";
			}
		} catch (Exception e) {
			reStr.add("2");
			log.error("积分转换异常："+e.getMessage());
			e.printStackTrace();
		}
		return checkContain(reStr);
	}

	//111
	private String scoreConvert(String partnerId, String consNo, String orgNo,
			String score,  String reScore,
			Calendar calendar, String corporationId, String boundCorId)
			throws Exception {
		BigDecimal diffB;
		BigDecimal scaleMallB;
		BigDecimal scalePaltformB;
		String fromxml="";
		String toxml="";
		if(StringUtils.isNotBlank(partnerId)){//测试时可先跳过(!)============aaa============
			//如果用户已经在统一用户中心解绑，那么就不能进行积分转换；
			try{
				List<Map<String, String>> mapUSCs = new ArrayList<Map<String,String>>();
				
				ObjectMapper objectMapper = new ObjectMapper();
				Map<String,String> uscInfoMap=new HashMap<String,String>();
				uscInfoMap.put("tenant",Constant.TENANT_CODE_PARAM_VALUE);//默认此值即可
				uscInfoMap.put("member",Constant.APP_CODE_PERSONAL);//默认此值即可
				Map<String,String> quInfoMap =new HashMap<String,String>();
				quInfoMap.put("userId", partnerId);
				String uscInfo=objectMapper.writeValueAsString(uscInfoMap);
				String quInfo = objectMapper.writeValueAsString(quInfoMap);
				Map<String,String> paramMap=new HashMap<String,String>();
				paramMap.put("uscInfo",uscInfo);
				paramMap.put("quInfo",quInfo);
				log.info("usc接口调用传参"+ paramMap);
				String authUrl=uscBaseUrl+"/user/getPowerBindInfoList";
				SipRestAccessAgent agent = getAgent();
				log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->用电信息绑定列表，通过rpc获取绑定信息开始：" + partnerId);
				String resultJson = agent.post(authUrl,paramMap);
				log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->调用rpc返回账号-"+ partnerId +"-的绑定信息：" + resultJson);
				if(StringUtils.equals(Constant.RE_CODE_0000, JSON.parseObject(resultJson).getJSONObject("srvrt").getString("resultCode"))){
					String retVal = JSON.parseObject(resultJson).getJSONObject("bizrt").getString("powerUserList");
					if(StringUtils.isNotBlank(retVal) && (!"[]".equals(retVal))){							
						JSONArray jsonArray = JSON.parseObject(resultJson).getJSONObject("bizrt").getJSONArray("powerUserList");
						if(jsonArray != null){
							log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->解析绑定信息list为：" +jsonArray.toString());
							
							for (int i = 0; i < jsonArray.size(); i++) {  
							    JSONObject jaList = (JSONObject) jsonArray.get(i);  
							    if(jaList != null){
								    String applicationUserCode = jaList.getString("powerUserNo"); //用电编号
								    String provinceId = jaList.getString("provinceId");  	//网省编号
								    
								    Map<String, String> data = new HashMap<String, String>();
								    data.put("applicationUserCode", applicationUserCode);
								    data.put("provinceId", provinceId);
								    mapUSCs.add(data);
							    }
							}
						}
						
					}
				}
				log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->mapUSCs="+ mapUSCs.toString());
				Map<String, String> map = new HashMap<String, String>();
				map.put("provinceId",  orgNo);
				map.put("applicationUserCode", consNo);
				log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->map="+ map.toString());
				if(mapUSCs != null && mapUSCs.size() >0){
						if(!mapUSCs.contains(map)){
							log.info("++++++++++++++++++++EcBpExchangeManagerServiceImpl-->scoreConvert-->return 11++++++++++++++++++++++");
							return "11";
						}
				}else{
					log.info("++++++++++++++++++++EcBpExchangeManagerServiceImpl-->scoreConvert-->else return 11++++++++++++++++++++++");
					return "11";
				}
			}catch (Exception e) {
				log.error("获取统一用户绑定数据信息时发生异常！", e);
				e.printStackTrace();
			}
		}
			
		String retVal ="0";
		//orgNo 网省编码    consNo  用电编号
		String key="GET_SCORE_CONVERT_LOCK"+ orgNo +consNo;
		//Memcached  加锁
//		Boolean flag   = redisTem.add(key, 60*10,partnerId).get();//测试时可直接赋值true============aaa============
		Boolean flag   = true;//测试时可直接赋值true============aaa============
		Map<String,Object> queryScoreConvert = new HashMap<String, Object>();
		String uuid = UUIDGenerator.getInstance().getReplaceUUID();//这个获取uuid的方法需要提取出来============aaa============
		String remark = "转换失败【"+consNo+"】";
		int reB=0;
		int newScore =0;
		if(flag){
			/**
			 * 为了实现并发控制
			 * 
			 * 	先 更新积分池的数据，再查询判断
			 * 			如果 >=0,则进行兑换
			 * 			否则，再还原积分池积分
			 */
			
			score = score+":"+reScore;
			log.info("******************************EcBpExchangeManagerServiceImpl-->scoreConvert-->"+orgNo+","+corporationId+"******************************");
			//查询网省积分池
			Map<String,Object> provinceMap = this.ecbpExchangeServiceImpl.selectProvince(orgNo,corporationId);
			log.info("EcBpExchangeManagerServiceImpl.java--->scoreConvert-->provinceMap："+provinceMap.toString());
			if(provinceMap!=null&&provinceMap.size()!=0){
				if(Integer.valueOf(provinceMap.get("CORPORATION_OVALUE").toString()) >0){//网省积分大于0时
					calendar.setTime(new Date());
					//获取合作平台积分比例
					Map<String,Object> mapExchange = this.queryCorExchange(corporationId, orgNo, calendar.getTime());
					log.info("EcBpExchangeManagerServiceImpl.java--->scoreConvert-->mapExchange："+mapExchange.toString());
					if(mapExchange!=null && mapExchange.size()!=0){
						//转换积分
						diffB = new BigDecimal(score.split(":")[0]);
						scaleMallB = new BigDecimal(Integer.valueOf(mapExchange.get("SCALE_MALL").toString()));
						scalePaltformB = new BigDecimal(Integer.valueOf(mapExchange.get("SCALE_PALTFORM").toString()));
						 reB = diffB.multiply(scaleMallB).divide(scalePaltformB,0, BigDecimal.ROUND_DOWN).intValue();//转换后商城积分		
						//网省积分大于0时
						if(reB>0){
							 newScore = new BigDecimal(reB).multiply(scalePaltformB).divide(scaleMallB).intValue();
							//更新积分池 数据
							ecbpExchangeServiceImpl.updateBpProvince(reB, reB, corporationId, orgNo);
							log.info("转换后商城积分：" + reB);
							//查询网省积分池
							Map<String,Object> updAfter = this.ecbpExchangeServiceImpl.selectProvince(orgNo,corporationId);
							log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->查询网省积分池返回结果："+updAfter.toString());
							//如果转换商城积分reB小于1，则不转
							if(Integer.valueOf(updAfter.get("CORPORATION_OVALUE").toString()) >=0){
								String convertTime = sdf.format(new Date());
								
								//时时推数据
								String successOrFail="0";
								
								try{
									if(getIsOpenProvince(orgNo)){
										//95598积分转换接口
//										queryScoreConvert = this.gdtServiceImpl.queryScoreConvertForNew(consNo,
//												orgNo,
//												Integer.valueOf(score.split(":")[0]).toString(),
//												Integer.valueOf(reB).toString(),
//												convertTime,
//												uuid);
//										newScore = Integer.valueOf(score.split(":")[0]);
//										reB = Integer.valueOf(score.split(":")[0]);
										
										//该省份不支持手动转换，只支持统一积分平台推送转换！
										retVal="15";
									}else{
										//95598积分转换接口
//										queryScoreConvert = this.gdtServiceImpl.queryScoreConvert(consNo,
//												orgNo,
//												Integer.valueOf(newScore).toString(),
//												Integer.valueOf(reB).toString(),
//												convertTime,
//												uuid);
										queryScoreConvert.put("code", "1");//先使用固定值测试============aaa====================
									}
									
									log.info("EcBpExchangeManagerServiceImpl-->scoreConvert-->调用积分接口返回信息："+queryScoreConvert.toString());
									if(queryScoreConvert!=null&&queryScoreConvert.size()!=0){
										if("1".equals(queryScoreConvert.get("code").toString())){
											calendar.setTime(new Date());
											int syScore = Integer.valueOf(score.split(":")[1])-newScore;
											this.ecbpExchangeServiceImpl.saveCoverScorePro(String.valueOf(newScore),boundCorId,uuid
													, partnerId, reB, calendar, orgNo, corporationId,consNo,
													String.valueOf(syScore),"");
											successOrFail="1";
											remark = "转换成功【"+consNo+"】";
										}else{
											log.info("scoreConvert++++++++++++++++++++++updateBpProvinceFH:++++++++++reB"+reB+"+++++++++++++corporationId"+corporationId+"++++++++++++++++++orgNo"+orgNo);
											ecbpExchangeServiceImpl.updateBpProvinceFH(reB, reB, corporationId, orgNo);
											//return "{'flag': '1','message':'兑换积分不能超过积分池剩余积分！'}";
											retVal="9";
										}
									}else{//2 接口未返回详情数据
										retVal="2";
										log.info("scoreConvert++++++++++++++++++++++//2 接口未返回详情数据");
									}
								}catch(Exception e){
									retVal="2";
									log.error("转换错误："+e.getMessage());
									e.printStackTrace();
								}finally{
									this.ecbpExchangeServiceImpl.saveBpMemberflowRecord(uuid, partnerId, String.valueOf(reB),String.valueOf(newScore),
											calendar.getTime(), remark, String.valueOf(calendar.get(Calendar.YEAR)), boundCorId, orgNo, successOrFail);
								}
								
								/*String re = this.saveCoverScorePro(orgNo, corporationId, calendar,score, diffB, scaleMallB, scalePaltformB, partnerId, boundCorId, consNo,0);
								reStr.add(re);*/
						
							}else{
								//还原积分池数据
								ecbpExchangeServiceImpl.updateBpProvinceFH(reB, reB, corporationId, orgNo);
								//return "{'flag': '1','message':'兑换积分不能超过积分池剩余积分！'}";
								retVal="4";
							}
						}else{
							retVal="12";//输入积分值太小
						}
						
					
					}else{
						retVal="3";
						log.info("scoreConvert++++++++++++++++++++++++++++++mapExchange!=null && mapExchange.size()!=0");
					}
				}else{
					retVal="4";
					log.info("scoreConvert++++++++++++++++++++++++++++++网省积分不大于0");
				}
			}else{
				retVal="3";
				log.info("scoreConvert+++++++++++++++++++++++++++++provinceMap!=null&&provinceMap.size()!=0");
			}

//			spyMemcachedClient.delete(key);//先注释掉=============aaa=============================
			redisTem.delete(key);//这个是放弃memcached，使用redis=============aaa=============================
		}else{
			retVal="5";
		}
		//进行转换日志插入操作
		
		//进去请求日志插入操作
		insertEcRequestLog(uuid,queryScoreConvert,fromxml,toxml,reB,newScore,remark,orgNo,retVal,"2",consNo,partnerId);
		return retVal;
	}

	//111
	private  SipRestAccessAgent getAgent(){
//		String url = SgccMallUtil.getInstance().getConfValue("site.sip.H5.url");
//		String account = SgccMallUtil.getInstance().getConfValue("site.sip.H5.account");
//		String pwd = SgccMallUtil.getInstance().getConfValue("site.sip.H5.pwd");
//		String secretKey = SgccMallUtil.getInstance().getConfValue("site.sip.H5.secretKey");
		//使用下面的方法===================================================================================
		String url = ecSystemParamMapper.getEcSystemparam("site.sip.H5.url").getParamvalue();
		String account = ecSystemParamMapper.getEcSystemparam("site.sip.H5.account").getParamvalue();
		String pwd = ecSystemParamMapper.getEcSystemparam("site.sip.H5.pwd").getParamvalue();
		String secretKey = ecSystemParamMapper.getEcSystemparam("site.sip.H5.secretKey").getParamvalue();
		
		log.info("url--->"+url);
		log.info("account--->"+account);
		log.info("pwd--->"+pwd);
		log.info("secretKey--->"+secretKey);
		log.info("uscBaseUrl--->"+uscBaseUrl);
//		String  url = "http://sip.esgmallt.com/sip/authz/gettoken"; 
//		String  pwd = "1234abcd"; 
//		String  secretKey = "64720680B1789DE72CB85102C73430D0"; 
//		String  account = "usc_test"; 
//		String  uscBaseUrl = "https://usc.esgmallt.com";
		SipRestAccessAgentFactory factory = new SipRestAccessAgentFactory(url,account,pwd,secretKey,"");
		SipRestAccessAgent agent=factory.getInstance();
		return agent;
	}
	
	//111
	//取得系统参数orgNoArray 【已开通积分推送转换的网省列表】
	public boolean getIsOpenProvince(String orgNo){
		EcSystemparam ecSystemPara = ecSystemParamMapper.getEcSystemparam("mall.corporation.tyjf.provinces.ids");
		boolean isOpenProvince = false;
		String province_ids = ecSystemPara.getParamvalue();
		
		int i;
		log.info("EcBpExchangeManagerServiceImpl->getIsOpenProvince:province_ids="+province_ids+"orgNo="+orgNo);
		if(!StringUtil.isNull(province_ids) && StringUtil.isNotNull(orgNo))
		{
			i = province_ids.indexOf(orgNo);
			if(i < 0 )
			{
				isOpenProvince =  false;
			}else
			{
				isOpenProvince =  true;
			}
		}
		log.info("EcBpExchangeManagerServiceImpl->getIsOpenProvince：isOpenProvince="+isOpenProvince);
		return isOpenProvince;		
	}
	
	@Override
	public int insertEcRequestLog(String uuid,Map<String,Object> map,String fromxml,String toxml,int reB,int newScore,String remark,String orgNo,String stats,String  orgtype,String consNo,String partnerId )
	{
		int i=0;
		try
		{
			EcRequestLog rlog = new EcRequestLog();
			rlog.setId(uuid);
			if(map!=null)
			{
				if(map.get("fromxml")!=null)
				{
					fromxml=map.get("fromxml").toString();
					if(fromxml.length()>4000)
					{
						fromxml=fromxml.substring(1,4000);
					}
					rlog.setFromxml(fromxml);
				}
				if(map.get("toxml")!=null)
				{
					toxml=map.get("toxml").toString();
					if(toxml.length()>4000)
					{
						toxml=toxml.substring(1,4000);
					}
					rlog.setToxml(toxml);
				}
			}
			rlog.setPartnerId(partnerId);
			rlog.setCreatetime(new Date());
			rlog.setApplicationUserCode(consNo);
			rlog.setMsg(remark);
			rlog.setFromvalue(String.valueOf(reB));
			rlog.setTovalue(String.valueOf(newScore));
			rlog.setOrgType(orgtype);
			rlog.setOrgId(orgNo);
			rlog.setStats(stats);
			i=ecRequestLogMapper.insertSelective(rlog);
		}catch (Exception e) {
			log.error("查询EcRequestLog日志表异常");
			e.printStackTrace();
		}
		return i;
	}
}